package me.xADudex.RandomLocation;

import org.bukkit.plugin.*;
import java.util.*;
import java.io.*;
import org.bukkit.entity.*;
import org.bukkit.command.*;
import org.bukkit.inventory.*;
import org.bukkit.*;

public class ZoneManager
{
    private Main pl;
    private ArrayList<Zone> zones;
    int tryLoadDelay;
    int checking;
    HashMap<String, Location> stillPlayers;
    HashMap<UUID, Location> playersTeleportToZoneLog;
    final Runnable load;
    final Runnable backup;

    public ZoneManager(final Main main) {
        this.zones = new ArrayList<Zone>();
        this.tryLoadDelay = 5;
        this.checking = 0;
        this.stillPlayers = new HashMap<String, Location>();
        this.playersTeleportToZoneLog = new HashMap<UUID, Location>();
        this.load = new Runnable() {
            @Override
            public void run() {
                if (Bukkit.isPrimaryThread()) {
                    Bukkit.getScheduler().runTaskAsynchronously((Plugin)ZoneManager.this.pl, (Runnable)this);
                    return;
                }
                if (ZoneManager.this.zones.isEmpty()) {
                    Bukkit.getScheduler().runTaskLaterAsynchronously((Plugin)ZoneManager.this.pl, ZoneManager.this.load, (long)ZoneManager.this.tryLoadDelay);
                    return;
                }
                final Zone z = ZoneManager.this.zones.get(ZoneManager.this.checking);
                final int maxLocs = ZoneManager.this.pl.getConfig().getInt("Performance.MaxLocationsStoredPerZone");
                if (z.locs.size() >= maxLocs) {
                    final ArrayList<Location> list = new ArrayList<Location>();
                    list.addAll(z.locs.keySet());
                    for (final Location loc : list) {
                        if (!z.checkChunk(loc.getBlockX() / 16, loc.getBlockZ() / 16)) {
                            z.locs.remove(loc);
                        }
                        else {
                            int X = loc.getBlockX() % 16;
                            int Z = loc.getBlockZ() % 16;
                            if (X < 0) {
                                X = 16 - X;
                            }
                            if (Z < 0) {
                                Z = 16 - Z;
                            }
                            final ChunkCoord cc = new ChunkCoord(loc.getBlockX() % 16, loc.getBlockZ() % 16);
                            if (cc.getX() < 0) {
                                cc.setX(16 + cc.getX());
                            }
                            if (cc.getZ() < 0) {
                                cc.setZ(16 + cc.getZ());
                            }
                            if (z.checkLocation(z.locs.get(loc), cc, loc.getBlockY())) {
                                continue;
                            }
                            z.locs.remove(loc);
                        }
                    }
                }
                if (z.locs.size() < maxLocs) {
                    Bukkit.getScheduler().runTask((Plugin)ZoneManager.this.pl, (Runnable)new Runnable() {
                        @Override
                        public void run() {
                            final ChunkSnapshot cs = z.getRandomChunkSnapshot();
                            if (cs != null) {
                                Bukkit.getScheduler().runTaskAsynchronously((Plugin)ZoneManager.this.pl, (Runnable)new Runnable() {
                                    @Override
                                    public void run() {
                                        z.loadLocation(cs);
                                        Bukkit.getScheduler().runTaskLaterAsynchronously((Plugin)ZoneManager.this.pl, ZoneManager.this.load, (long)ZoneManager.this.tryLoadDelay);
                                    }
                                });
                            }
                            else {
                                Bukkit.getScheduler().runTaskLaterAsynchronously((Plugin)ZoneManager.this.pl, ZoneManager.this.load, (long)ZoneManager.this.tryLoadDelay);
                            }
                        }
                    });
                }
                else {
                    Bukkit.getScheduler().runTaskLaterAsynchronously((Plugin)ZoneManager.this.pl, ZoneManager.this.load, (long)ZoneManager.this.tryLoadDelay);
                }
                final ZoneManager this$0 = ZoneManager.this;
                ++this$0.checking;
                if (ZoneManager.this.checking >= ZoneManager.this.zones.size()) {
                    ZoneManager.this.checking = 0;
                }
            }
        };
        this.backup = new Runnable() {
            @Override
            public void run() {
                System.out.println("======================   Backup Manager   ======================");
                ZoneManager.this.pl.getLogger().info("Saving zones...");
                ZoneManager.this.saveAll();
                ZoneManager.this.pl.getLogger().info("Starting backup...");
                String date = new Date().toString();
                final String[] array = date.split(" ");
                date = String.valueOf(array[0]) + " " + array[1] + " " + array[2] + " " + array[3].replaceAll(":", "-") + " " + array[5];
                File backupFolder = new File(ZoneManager.this.pl.getDataFolder(), "Backups");
                final int maxBackups = ZoneManager.this.pl.getConfig().getInt("Backup.MaxBackups");
                if (maxBackups > 0 && backupFolder.list() != null) {
                    while (backupFolder.list().length >= maxBackups) {
                        backupFolder.listFiles()[0].delete();
                    }
                }
                if (!backupFolder.exists()) {
                    backupFolder.mkdirs();
                }
                backupFolder = new File(backupFolder, String.valueOf(date) + ".zip");
                FileTools.zipFiles(backupFolder, new File(ZoneManager.this.pl.getDataFolder(), "zones.txt"), new File(ZoneManager.this.pl.getDataFolder(), "config.yml"), new File(ZoneManager.this.pl.getDataFolder(), "playersLog.txt"));
                ZoneManager.this.pl.getLogger().info("Successfully saved zones and made backup");
                System.out.println("================================================================");
                if (!ZoneManager.this.pl.isDisabling()) {
                    final int interval = ZoneManager.this.pl.getConfig().getInt("Backup.BackupInterval");
                    if (interval > 0 && ZoneManager.this.pl.getConfig().getBoolean("Backup.Enable")) {
                        Bukkit.getScheduler().runTaskLaterAsynchronously((Plugin)ZoneManager.this.pl, ZoneManager.this.backup, (long)(interval * 20));
                    }
                }
            }
        };
        this.pl = main;
    }

    public void startTask() {
        if (this.pl.getConfig().getInt("Backup.BackupInterval") > 0) {
            Bukkit.getScheduler().runTaskAsynchronously((Plugin)this.pl, this.backup);
        }
        Bukkit.getScheduler().runTaskAsynchronously((Plugin)this.pl, this.load);
    }

    public void save(final Zone z) {
        final File f = new File(this.pl.getDataFolder(), "zones.txt");
        String all = FileTools.read(f);
        if (all.startsWith("\n")) {
            all.replaceFirst("\n", "");
        }
        final String toString = new StringBuilder(String.valueOf(z.toString())).toString();
        if (!all.contains("\n" + z.getName()) && !all.contains(String.valueOf(z.getName()) + "\n") && !all.startsWith(z.getName())) {
            all = String.valueOf(all) + "\n" + toString;
        }
        else {
            all = all.replaceAll(String.valueOf(z.getName()) + "[^\n]*", toString);
        }
        if (all.startsWith("\n")) {
            all.replaceFirst("\n", "");
        }
        FileTools.write(f, all);
    }

    public void saveAll() {
        String all = "";
        for (final Zone z : this.zones) {
            all = String.valueOf(all) + "\n" + z.toString();
        }
        if (all.startsWith("\n")) {
            all.replaceFirst("\n", "");
        }
        final File f = new File(this.pl.getDataFolder(), "zones.txt");
        FileTools.write(f, all);
        String playersTeleportLog = null;
        for (final Map.Entry<UUID, Location> e : this.playersTeleportToZoneLog.entrySet()) {
            final String line = e.getKey() + ": " + e.getValue().getWorld().getName() + "," + e.getValue().getX() + "," + e.getValue().getY() + "," + e.getValue().getZ() + "," + e.getValue().getYaw() + "," + e.getValue().getPitch();
            if (playersTeleportLog == null) {
                playersTeleportLog = line;
            }
            else {
                playersTeleportLog = String.valueOf(playersTeleportLog) + "\n" + line;
            }
        }
//        final File playersLog = new File(this.pl.getDataFolder(), "playersLog.txt");
//        if (!playersLog.exists()) {
//            try {
//                playersLog.createNewFile();
//            }
//            catch (IOException e2) {
//                this.pl.getLogger().warning("Could not create playersLog.txt! Might be caused by deneided write access or file creationg error");
//                e2.printStackTrace();
//            }
//        }
//        if (playersTeleportLog != null) {
        //阉割记录传送日志的功能，该功能会导致日志过大时无法开启or关闭服务器
//            FileTools.write(playersLog, playersTeleportLog);

//        }
    }

    public void loadAll() {
        final File f = new File(this.pl.getDataFolder(), "zones.txt");
        boolean zoneLoaded = false;
        if (f.exists()) {
            final String zones = FileTools.read(f);
            if (zones != null) {
                String[] split2;
                for (int length = (split2 = zones.split("\n")).length, i = 0; i < length; ++i) {
                    final String key = split2[i];
                    final String[] args = key.split(",");
                    if (!args[0].equals("")) {
                        final Zone z = new Zone(args[0]);
                        z.loadFromString(key);
                        zoneLoaded = true;
                        this.zones.add(z);
                    }
                }
            }
        }
        if (!zoneLoaded) {
            this.pl.getLogger().info("Found no zones to load!");
        }
        // 此处为load传送日志问题，若日志过大，将导致主线程卡死，已阉割
//        final File playersLog = new File(this.pl.getDataFolder(), "playersLog.txt");
//        int erros = 0;
//        if (playersLog.exists()) {
//            final String list = FileTools.read(playersLog);
//            if (list != null) {
//                String[] split3;
//                for (int length2 = (split3 = list.split("\n")).length, j = 0; j < length2; ++j) {
//                    final String line = split3[j];
//                    if (!line.replaceAll(" ", "").equals("")) {
//                        try {
//                            final String[] split = line.split(": ");
//                            final String[] locArgs = split[1].split(",");
//                            final UUID uuid = UUID.fromString(split[0]);
//                            final World w = Bukkit.getWorld(locArgs[0]);
//                            if (w != null) {
//                                final Location loc = new Location(w, Double.parseDouble(locArgs[1]), Double.parseDouble(locArgs[2]), Double.parseDouble(locArgs[3]), Float.parseFloat(locArgs[4]), Float.parseFloat(locArgs[5]));
//                                this.playersTeleportToZoneLog.put(uuid, loc);
//                            }
//                        }
//                        catch (Exception e) {
//                            this.pl.getLogger().warning("Error while loading player log for player: " + line.split(": ")[0]);
//                            this.pl.getLogger().warning(e.getMessage());
//                            this.pl.getLogger().warning(" --> Entry Deleted!");
//                            ++erros;
//                        }
//                    }
//                }
//            }
//        }
//        this.pl.getLogger().info("Loaded " + this.playersTeleportToZoneLog.size() + " players with " + erros + " errors");
    }

    public boolean createZone(final String name) {
        if (name == null) {
            return false;
        }
        if (name.equals("")) {
            return false;
        }
        for (final Zone z : this.zones) {
            if (z.getName().equalsIgnoreCase(name)) {
                return false;
            }
        }
        Zone z = new Zone(name);
        this.zones.add(z);
        this.save(z);
        return true;
    }

    public String removeZone(final String name) {
        final Zone z = this.getZone(name);
        if (z != null) {
            this.zones.remove(z);
            this.saveAll();
            return z.getName();
        }
        return null;
    }

    public void teleportPlayer(final Player p, final CommandSender teleporter, final String name, final TeleportSource source) {
        if (!this.cooldownCheck(p, source)) {
            return;
        }
        final TeleportResult tr = this.teleport(p, name, source);
        if (tr.equals(TeleportResult.SUCCEED)) {
            String pname = String.valueOf(p.getName()) + " ";
            if (teleporter.getName().equalsIgnoreCase(p.getName())) {
                pname = "";
            }
            if (this.pl.getConfig().getBoolean("MessageOnTeleport")) {
                final int time = this.pl.getConfig().getInt("MoveRestriction.Time");
                if (this.pl.getConfig().getBoolean("MoveRestriction.Enable") && time > 0 && !p.hasPermission("RandomLocation.Admin") && !p.hasPermission("RandomLocation.MoveRestrictionBypass")) {
                    teleporter.sendMessage(ChatColor.GREEN + "Please stand still for " + time + "s");
                }
                else {
                    teleporter.sendMessage(ChatColor.GREEN + "随机传送成功 ");
                }
            }
            this.addCooldown(p, source);
        }
        else if (tr.equals(TeleportResult.NO_LOC)) {
            teleporter.sendMessage(ChatColor.GREEN + "没有找到一个可传送点坐标点");
        }
        else if (tr.equals(TeleportResult.NO_ZONE)) {
            teleporter.sendMessage(ChatColor.GREEN + "未找到传送区域:" + name);
        }
        else if (tr.equals(TeleportResult.NO_PERM)) {
            teleporter.sendMessage(ChatColor.DARK_RED + "你没有获取传送到这个区域的权限");
        }
        else if (tr.equals(TeleportResult.RANGE_ERROR)) {
            teleporter.sendMessage(ChatColor.DARK_RED + "传送错误,请联系管理员,错误编码[1]");
        }
        else if (tr.equals(TeleportResult.TYPE_ERROR)) {
            teleporter.sendMessage(ChatColor.GREEN + "区域" + this.getZoneName(name) + " 不是一个传送区域");
        }
        else if (tr.equals(TeleportResult.PAY_ERROR)) {
            double price = this.pl.getConfig().getDouble("Economy.Price");
            if (price < 0.0) {
                price = 0.0;
            }
            teleporter.sendMessage(ChatColor.GREEN + "你的金币不足,你至少需要" + price + "金币" + ((price == 1.0) ? this.pl.econ.currencyNameSingular() : this.pl.econ.currencyNamePlural()));
        }
    }

    private TeleportResult teleport(final Player p, final String name, final TeleportSource source) {
        for (final Zone z : this.zones) {
            if (z.getName().equalsIgnoreCase(name)) {
                if (!z.getType().equals(ZoneType.TELEPORT)) {
                    return TeleportResult.TYPE_ERROR;
                }
                if (!source.equals(TeleportSource.OVERRIDE)) {
                    if (!p.hasPermission("RandomLocation.Admin") && !p.hasPermission("RandomLocation.Use") && this.pl.getConfig().getBoolean("Permissions.UsePermissions") && (!source.equals(TeleportSource.PORTAL) || !p.hasPermission("RandomLocation.UsePortal")) && (!source.equals(TeleportSource.SIGN) || !p.hasPermission("RandomLocation.UseSign")) && (!source.equals(TeleportSource.COMMAND) || !p.hasPermission("RandomLocation.UseCommand"))) {
                        return TeleportResult.NO_PERM;
                    }
                    if (!p.hasPermission("RandomLocation." + z.getPerm()) && !z.getPerm().equalsIgnoreCase("none")) {
                        return TeleportResult.NO_PERM;
                    }
                    if (!z.rangeCheck(p) && !p.hasPermission("RandomLocation.Admin")) {
                        return TeleportResult.RANGE_ERROR;
                    }
                }
                return z.teleport(p, source);
            }
        }
        return TeleportResult.NO_ZONE;
    }

    void addCooldown(final Player p, final TeleportSource source) {
        if (!p.hasPermission("RandomLocation.Admin") && !p.hasPermission("RandomLocation.CooldownBypass")) {
            if (source.equals(TeleportSource.COMMAND)) {
                this.pl.timer.addcmds(p, this.pl.getConfig().getInt("Cooldowns.Commands"));
            }
            else if (source.equals(TeleportSource.PORTAL)) {
                this.pl.timer.addPortals(p, this.pl.getConfig().getInt("Cooldowns.Portals"));
            }
            else if (source.equals(TeleportSource.SIGN)) {
                this.pl.timer.addSigns(p, this.pl.getConfig().getInt("Cooldowns.Signs"));
            }
        }
    }

    boolean canPay(final Player p, final TeleportSource source) {
        if (!p.hasPermission("RandomLocation.Admin") && this.pl.useVaultHook() && !source.equals(TeleportSource.OVERRIDE)) {
            final double price = this.pl.getConfig().getDouble("Economy.Price");
            if (price >= 0.0) {
                return this.pl.econ.has((OfflinePlayer)p, price) || this.pl.econ.has((OfflinePlayer)p, p.getWorld().getName(), price);
            }
        }
        return true;
    }

    boolean pay(final Player p, final TeleportSource source) {
        if (!p.hasPermission("RandomLocation.Admin") && this.pl.useVaultHook() && !source.equals(TeleportSource.OVERRIDE)) {
            double price = this.pl.getConfig().getDouble("Economy.Price");
            if (price < 0.0) {
                price = 0.0;
            }
            return this.pl.econ.withdrawPlayer((OfflinePlayer)p, price).transactionSuccess() || this.pl.econ.withdrawPlayer((OfflinePlayer)p, p.getWorld().getName(), price).transactionSuccess();
        }
        return true;
    }

    void payBack(final Player p) {
        if (!p.hasPermission("RandomLocation.Admin") && this.pl.useVaultHook()) {
            double price = this.pl.getConfig().getDouble("Economy.Price");
            if (price < 0.0) {
                price = 0.0;
            }
            if (!this.pl.econ.depositPlayer((OfflinePlayer)p, price).transactionSuccess()) {
                this.pl.econ.depositPlayer((OfflinePlayer)p, p.getWorld().getName(), price);
            }
        }
    }

    public boolean cooldownCheck(final Player p, final TeleportSource source) {
        if (!p.hasPermission("RandomLocation.Admin") && !p.hasPermission("RandomLocation.CooldownBypass")) {
            if (source.equals(TeleportSource.COMMAND)) {
                if (this.pl.timer.cmdsContains(p)) {
                    p.sendMessage(ChatColor.GREEN + "You have to wait " + this.pl.timer.getCmdTimeLeft(p) + "s before you can use that command again");
                    return false;
                }
                return true;
            }
            else if (source.equals(TeleportSource.PORTAL)) {
                if (this.pl.timer.portalsContains(p)) {
                    p.sendMessage(ChatColor.GREEN + "You have to wait " + this.pl.timer.getPortalTimeLeft(p) + "s before you can use that portal again");
                    return false;
                }
                return true;
            }
            else if (source.equals(TeleportSource.SIGN)) {
                if (this.pl.timer.signsContains(p)) {
                    p.sendMessage(ChatColor.GREEN + "You have to wait " + this.pl.timer.getSignTimeLeft(p) + "s before you can use that sign again");
                    return false;
                }
                return true;
            }
        }
        return true;
    }

    public String setPos(final String name, final Location loc, final boolean first) {
        for (final Zone z : this.zones) {
            if (z.getName().equalsIgnoreCase(name)) {
                z.setPos(loc, first);
                return z.getName();
            }
        }
        return null;
    }

    public String setType(final String name, final ZoneType type) {
        for (final Zone z : this.zones) {
            if (z.getName().equalsIgnoreCase(name)) {
                if (type != null) {
                    z.setType(type);
                }
                return z.getName();
            }
        }
        return null;
    }

    public String setPortalDest(final String portal, final String dest) {
        for (final Zone z : this.zones) {
            if (z.getName().equalsIgnoreCase(portal)) {
                if (!z.getType().equals(ZoneType.PORTAL)) {
                    return "§NonPortal";
                }
                final Zone destZone = this.getZone(dest);
                if (destZone == null) {
                    return "§NonDest";
                }
                if (destZone.getType().equals(ZoneType.TELEPORT)) {
                    z.setPortalDest(destZone.getName());
                    return String.valueOf(z.getName()) + "§" + destZone.getName();
                }
                return "§NonTeleportDest";
            }
        }
        return null;
    }

    public String getZoneName(final String zone) {
        for (final Zone z : this.zones) {
            if (z.getName().equalsIgnoreCase(zone)) {
                return z.getName();
            }
        }
        return null;
    }

    public Zone getZone(final String zone) {
        for (final Zone z : this.zones) {
            if (z.getName().equalsIgnoreCase(zone)) {
                return z;
            }
        }
        return null;
    }

    public String getList() {
        String tp = "Teleport:";
        String p = "Portal:";
        String ntp = "NonTeleport:";
        for (final Zone z : this.zones) {
            if (z.getType().equals(ZoneType.NON_TELEPORT)) {
                ntp = String.valueOf(ntp) + "\n" + z.getName();
            }
            else if (z.getType().equals(ZoneType.PORTAL)) {
                p = String.valueOf(p) + "\n" + z.getName();
            }
            else {
                tp = String.valueOf(tp) + "\n" + z.getName();
            }
        }
        final String total = StringTools.mergeStrings(54, 3, "\n", tp, p, ntp);
        String result = null;
        String[] split;
        for (int length = (split = total.split("\n")).length, i = 0; i < length; ++i) {
            final String line = split[i];
            if (result == null) {
                result = ChatColor.GOLD + line;
            }
            else {
                result = String.valueOf(result) + "\n" + ChatColor.DARK_GREEN + line;
            }
        }
        return ChatColor.GRAY + "Total Zones: " + this.zones.size() + "\n" + result;
    }

    public String getInfo(final String zone) {
        for (final Zone z : this.zones) {
            if (z.getName().equalsIgnoreCase(zone)) {
                return z.getInfo();
            }
        }
        return null;
    }

    public String setPerm(final String name, String perm) {
        for (final Zone z : this.zones) {
            if (z.getName().equalsIgnoreCase(name)) {
                if (perm == null) {
                    perm = "none";
                }
                if (perm.equals("")) {
                    perm = "none";
                }
                z.setPerm(perm);
                return z.getName();
            }
        }
        return null;
    }

    public String setUseRange(final String name, final boolean flag) {
        for (final Zone z : this.zones) {
            if (z.getName().equalsIgnoreCase(name)) {
                z.setUseRange(flag);
                return z.getName();
            }
        }
        return null;
    }

    public String setRange(final String name, final int range) {
        for (final Zone z : this.zones) {
            if (z.getName().equalsIgnoreCase(name)) {
                z.setRange(range);
                return z.getName();
            }
        }
        return null;
    }

    public String setRangeFrom(final String name, final RangeFrom from) {
        for (final Zone z : this.zones) {
            if (z.getName().equalsIgnoreCase(name)) {
                z.setRangeFrom(from);
                return z.getName();
            }
        }
        return null;
    }

    public String setKeepDirection(final String name, final boolean flag) {
        for (final Zone z : this.zones) {
            if (z.getName().equalsIgnoreCase(name)) {
                z.setKeepDirection(flag);
                return z.getName();
            }
        }
        return null;
    }

    public String setMode(final String zone, final SpawnOn spawnOn) {
        for (final Zone z : this.zones) {
            if (z.getName().equalsIgnoreCase(zone)) {
                z.setMode(spawnOn);
                return z.getName();
            }
        }
        return null;
    }

    public String setGroundBlocks(final String zone, final BlockData[] blocks) {
        for (final Zone z : this.zones) {
            if (z.getName().equalsIgnoreCase(zone)) {
                z.setGroundBlocks(blocks);
                return z.getName();
            }
        }
        return null;
    }

    public String setTopBlocks(final String zone, final BlockData[] blocks) {
        for (final Zone z : this.zones) {
            if (z.getName().equalsIgnoreCase(zone)) {
                z.setTopBlocks(blocks);
                return z.getName();
            }
        }
        return null;
    }

    public String setInvulnerability(final String zone, final int seconds) {
        for (final Zone z : this.zones) {
            if (z.getName().equalsIgnoreCase(zone)) {
                z.setInvulnerability(seconds);
                return z.getName();
            }
        }
        return null;
    }

    public String setCustomRangeLocation(final String zone, final Location loc) {
        for (final Zone z : this.zones) {
            if (z.getName().equalsIgnoreCase(zone)) {
                z.setCustomRangeLocation(loc);
                return z.getName();
            }
        }
        return null;
    }

    public ArrayList<Zone> getPortals() {
        final ArrayList<Zone> list = new ArrayList<Zone>();
        for (final Zone z : this.zones) {
            if (z.getType().equals(ZoneType.PORTAL)) {
                list.add(z);
            }
        }
        return list;
    }

    public ArrayList<Zone> getNonTeleports() {
        final ArrayList<Zone> list = new ArrayList<Zone>();
        for (final Zone z : this.zones) {
            if (z.getType().equals(ZoneType.NON_TELEPORT)) {
                list.add(z);
            }
        }
        return list;
    }

    public boolean insideNonTeleports(final Location loc) {
        for (final Zone z : this.getNonTeleports()) {
            if (z.nonTeleportCheck(loc)) {
                return true;
            }
        }
        return false;
    }

    public String setItems(final String zone, final HashMap<Integer, ItemStack> items) {
        for (final Zone z : this.zones) {
            if (z.getName().equalsIgnoreCase(zone)) {
                z.setItems(items);
                return z.getName();
            }
        }
        return null;
    }

    public String setUseKit(final String zone, final boolean flag) {
        for (final Zone z : this.zones) {
            if (z.getName().equalsIgnoreCase(zone)) {
                z.setUseKit(flag);
                return z.getName();
            }
        }
        return null;
    }

    public Inventory getKit(final String zone) {
        for (final Zone z : this.zones) {
            if (z.getName().equalsIgnoreCase(zone)) {
                return z.getKit();
            }
        }
        return null;
    }

    boolean isLoadedZone(final Chunk c) {
        for (final Zone z : this.zones) {
            if (z.getNextLoc() != null && z.getNextLoc().getChunk().getX() == c.getX() && z.getNextLoc().getChunk().getZ() == c.getZ()) {
                return true;
            }
        }
        return false;
    }
}
